
var ImageFile;      
function listenFileSelect() {
    // listen for file selection
    var fileInput = document.getElementById("mypicInput"); // pointer #1

    // When a change happens to the File Chooser Input
    fileInput.addEventListener('change', function (e) {
        ImageFile = e.target.files[0];   //Global variable
        var blob = URL.createObjectURL(ImageFile);
        console.log(blob);
        updateImage(blob);
    })
}
listenFileSelect();

function updateImage(imageblob) {
    const image = document.getElementById("mypic-goes-here"); // pointer #2
    image.src = imageblob; // Display this image
}

function savePost() {
    // Gather the data from the form
    var calorieData = document.getElementById('calorieInput').value;
    var details = document.getElementById('detailsText').value;
    var image = document.getElementById('mypicInput').files[0]; // This will capture the file object
    var blob = URL.createObjectURL(image);
    console.log (image.name);

    // Create a JSON object with the data
    const now = new Date();
    const dformatted = now.toLocaleString('en-US', {
        weekday: 'short',  // "Monday", "Tuesday", etc.
        year: 'numeric',  // "2021", "2022", etc.
        month: 'short',    // "January", "February", etc.
        day: 'numeric',   // 1, 2, 3, etc.
        hour: 'numeric',  // 12 AM, 1 PM, etc.
        minute: 'numeric',
        second: 'numeric'
    });

    // Get the user's location
    
    var formData = {
        date: dformatted,       //save the date
        calories: calorieData,  //save the calorie entered
        details: details,
        // You cannot store file object directly into localStorage as it only supports strings.
        // Typically, you'd handle file uploads directly to a server or convert to a base64 string.
        imageName: image.name // Store image name as a reference
    };

    // Convert the JSON object to a string and store in local storage
    //localStorage.setItem('calorieFormData', JSON.stringify(formData));
    addToPostHistory(formData);
}

// This function will add data to the person WHO IS LOGGED IN
// into the history array
function addToPostHistory(data) {
    // read the current history array
    // push this add-event into the history array

    var who = JSON.parse(localStorage.getItem("loggedinUser"));
    if (who) {

        var users = JSON.parse(localStorage.getItem("users"));
        var email = who["email"];  //email of who is logged in
        console.log(email);        //debug

        if (users) {
            //find the person who is logged in, from the users collection
            const person = users.find(u => u.email === email);
            if (person) {
                if (person.history === null)      //if there are no users yet
                    person.history = [];          //initialize it to empty
                console.log(person.history);
                console.log(data);
                console.log(users);
                
                // pushes it to the "person" object
                person.history.push(data);

                //save it into Local Storage
		        localStorage.setItem("users", JSON.stringify(users));
                addCountLocalStorage(data.calories);
                alert('Data saved successfully!');
            }
        }
    } else {
        console.log("No one is logged in");
    }
}

function addCountLocalStorage(value){
    		// find out who is logged in
		var user = JSON.parse(localStorage.getItem("loggedinUser"));
		if (user) {
			console.log("Currently logged in:  " + user["name"]);

			//get the users collection, and update the count for THAT user
			updateUsersCountLocalStorage(user["email"], value);

		} else {
			console.log("No one is logged in");
		}

}

// This function will go to the "users" collection in Local Storage
// find the one that matches this email
// Updates the count value with the new value
// Saves it back to Local Storage

function updateUsersCountLocalStorage(email, value){
	var users = JSON.parse(localStorage.getItem("users"));
	if (users) {
		const person = users.find(u => u.email === email);
        person.count = parseInt(person.count) + parseInt(value);
		localStorage.setItem("users", JSON.stringify(users));
	}
}